package com.mspbots.tsheet.trigger;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mspbots.api.client.CoreClient;
import com.mspbots.cw.request.SheetsTimeDTO;
import com.mspbots.tsheet.model.TriggerEventDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Map;

import static com.mspbots.common.TriggerEvent.TSHEET_TIMES_NEW;

/**
 * com.mspbots.tsheet.trigger.TsheetTriggerEvent
 *
 * @author Jason
 * @date 2019/12/19
 **/

@Slf4j
@Component
public class TsheetTriggerEvent {

    @Autowired
    private RabbitMessagingTemplate messagingTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private CoreClient coreClient;


    //    @RabbitListener(queues = "trigger.tsheet.TsheetInCheck")
    public void publishTicketTriggerEvent(SheetsTimeDTO tsheetsTimeDTO) {
        if (tsheetsTimeDTO.getLastModified() != null && LocalDateTime.now().minusHours(24).isBefore(tsheetsTimeDTO.getLastModified())) {
            Map<String, Object> userMappingParam = Map.of(
                    "tenantId", tsheetsTimeDTO.getTenantId(),
                    "sheetUserId", tsheetsTimeDTO.getSheetUserId()
            );

            JsonNode userMapping = coreClient.get("/user-mapping/detail", userMappingParam).block();

            if (!ObjectUtils.isEmpty(userMapping)) {
                if (!ObjectUtils.isEmpty(userMapping) && userMapping.get("id") != null) {
                    log.info("user info : {}", userMapping.get("id"));
                    JsonNode payload = null;
                    try {
                        String payloadStr = objectMapper.writeValueAsString(tsheetsTimeDTO);
                        payload = objectMapper.readTree(payloadStr);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }

                    TriggerEventDTO triggerEventDTO = new TriggerEventDTO();
                    triggerEventDTO.setTenantId(userMapping.get("tenantId").asLong());
                    triggerEventDTO.setEventName(TSHEET_TIMES_NEW.getEvent());
                    triggerEventDTO.setScope(TSHEET_TIMES_NEW.getScope());
                    triggerEventDTO.setPayload(payload);
                    triggerEventDTO.setUserInfo(userMapping);

                    this.messagingTemplate.convertAndSend("msp.trigger.event", "", triggerEventDTO);
                    log.info("cw msp.trigger.event NewTsheet:[{}] ", this.objectMapper.convertValue(triggerEventDTO, JsonNode.class));
                } else {
                    log.info("tsheet user [{}] has no mapping [{}]", tsheetsTimeDTO, tsheetsTimeDTO.getSheetId());
                }
            }

        }
        // for bot1.0
//            this.messagingTemplate.convertAndSend("msp.trigger.tickets", "", tenantTicketDTO);


    }


    /**
     * test for dev
     */
//    @Scheduled(cron = "0/30 * * * * ?")
    public void test() {
//        Map<String, Object> params = new HashMap<>();
//        params.put("tenantId", 1);
//        params.put("cwId",263947);
//
//
//        JsonNode result = coreClient.get("/tickets/list",params).block();
//        List<SheetsTimeDTO> tenantTicketDTO = objectMapper.convertValue(result, new TypeReference<List<SheetsTimeDTO>>(){});
//        publishTicketTriggerEvent(tenantTicketDTO.get(0));
    }


}
